package com.xc.stock.domain.basic.factory;

import java.math.BigDecimal;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.ag.exception.SysTipsException;
import com.ag.utils.SysConstant;
import com.ag.utils.SysConstant.BooleanEnum;
import com.google.common.base.Joiner;
import com.xc.stock.constant.Currency;
import com.xc.stock.constant.RoleEnum;
import com.xc.stock.domain.basic.entity.Account;
import com.xc.stock.domain.basic.entity.TradeAcc;
import com.xc.stock.dto.model.AccountSelector;
import com.xc.stock.dto.model.DestInfo;
import com.xc.stock.utils.SpringUtils;

/**
 * AccountFactory
 *
 * @author xlfd
 * @email xlfd@gmail.com
 * @created 2022/03/25
 */
@Component
@Lazy
public class AccountFactory {
	int roleToNum(RoleEnum role) {
		if (role == RoleEnum.SYS) {
			return 1;
		} else if (role == RoleEnum.USER) {
			return 3;
		}

		throw new SysTipsException("账户不支持的角色[" + role.code() + "]");
	}
	
	int currencyToNum(Currency currency) {
		if (currency == Currency.CNY) {
			return 10;
		} else if (currency == Currency.HKD) {
			return 20;
		} else if (currency == Currency.USD) {
			return 30;
		}

		throw new SysTipsException("账户不支持的币种[" + currency.code() + "]");
	}

	public String accountNo(AccountSelector acc) {
		return Joiner.on("")
				.join(acc.getAccountType().prefix(), roleToNum(acc.getDest().getRe()), currencyToNum(acc.getCurrency()), acc.getDest().getId());
	}

	public Account entity(AccountSelector selector, TradeAcc tradeAcc, BigDecimal initAmount) {
		DestInfo dest = selector.getDest();
		RoleEnum role = selector.getDest().getRe();

		Account account = Account.builder()
				.accountNo(accountNo(selector))
				.accountType(selector.getAccountType().code())
				.currency(selector.getCurrency().code())
				.balance(initAmount)
				.destId(dest.getId())
				.destName(dest.getName())
				.destPhone(dest.getPhone())
				.lockAmount(BigDecimal.ZERO)
				.limitWithdrawAmount(BigDecimal.ZERO)
				.willIncomeAmount(BigDecimal.ZERO)
				.withdrawAmount(BigDecimal.ZERO)
				.role(role.code())
				.status(SysConstant.STATUS_NORMAL)
				.total(initAmount)
				.preTradingDay(BigDecimal.ZERO)
				.commission(BigDecimal.ZERO)
				.pId(selector.getPId())
				.stampTax(BigDecimal.ZERO)
				.recharge(BigDecimal.ZERO)
//				.source(stockSource != null ? stockSource.code() : null)
				.withdrawFlag(BooleanEnum.of(selector.getAccountType().withdrawFlag()).v())
				.build();
		account.putExt("tradeAcc", tradeAcc.thumb());
		return account;
	}

	public static AccountFactory of() {
		return SpringUtils.getBean(AccountFactory.class);
	}
}
